#include "usart.h"

void wing_usart1_init(
    uint32_t baudrate,
    uint16_t parity,
    uint16_t stopbits)
{    
    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;
     
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO,ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
    
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP ;        //TX - PA9, RX - PA10
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 ;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz ;
    GPIO_Init (GPIOA, &GPIO_InitStructure);
    
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_Init (GPIOA, &GPIO_InitStructure);
    
    USART_InitStructure.USART_BaudRate = baudrate;
    if(parity != USART_Parity_No)
            USART_InitStructure.USART_WordLength = USART_WordLength_9b; 
    else
            USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = stopbits;
    USART_InitStructure.USART_Parity = parity;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

    USART_Init(USART1, &USART_InitStructure);

    USART_Cmd(USART1, ENABLE);
}

void Board_USART_SendByte(USART_TypeDef* USARTx,unsigned char data)
{        
    while(USART_GetFlagStatus(USARTx, USART_FLAG_TC) == RESET){;}
    USART_SendData(USARTx, data);
    while(USART_GetFlagStatus(USARTx, USART_FLAG_TC) == RESET){;}
    
}

void wing_clear_buffer(u8* p, u16 len)
{
    u16 i = 0;
    for(i=0;i<len;i++)
        *p++ = 0;
}

/* RT-Thread console */
void rt_hw_console_output(const char *str)
{
    rt_size_t i = 0, size = 0;
    char a = '\r';

    size = rt_strlen(str);
    for (i = 0; i < size; i++)
    {
        if (*(str + i) == '\n')
        {
            Board_USART_SendByte(USART1, *(uint8_t *)&a);
        }
        Board_USART_SendByte(USART1, *(uint8_t *)(str + i));
    }
}

char rt_hw_console_getchar(void)
{
    int ch = -1;

    if (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) != RESET)
    {
        ch = USART_ReceiveData(USART1)&0xFF;
    }
    else
    {
        //ORE-读过载错误，当RXNE为1的时候收到新的数据
        if(USART_GetFlagStatus(USART1, USART_FLAG_ORE) != RESET)
        {
            USART_ClearFlag(USART1, USART_FLAG_ORE);
        }
        rt_thread_mdelay(10);
    }
    return ch;
}
